package com.mtsmda.jpa.dao.impl;

import java.sql.SQLException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import com.mtsmda.jpa.dao.BookDAOI;
import com.mtsmda.jpa.domain.Author;
import com.mtsmda.jpa.domain.Book;

public class BookDAO implements BookDAOI {

	public EntityManager entityManager = Persistence
			.createEntityManagerFactory("MTSMDA").createEntityManager();

	public EntityManager getEntityManager() {
		return entityManager;
	}

	@Override
	public boolean addBook(Book book) {
		try {
			entityManager.getTransaction().begin();
			Book merge = entityManager.merge(book);
			if (merge == null) {
				throw new SQLException("Not add to database!");
			}
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean updateBook(Book book) {
		return addBook(book);
	}

	@Override
	public boolean deleteBook(Book book) {
		try {
			entityManager.getTransaction().begin();
			entityManager.remove(book);
			entityManager.getTransaction().commit();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean deleteAllBooks() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Book getBookById(Integer idBook) {
		try {
			Book findBook = entityManager.find(Book.class, idBook);
			if (findBook == null) {
				throw new SQLException("Not found in database!");
			}
			return findBook;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<Book> getAllBooks() {
		try {
			TypedQuery<Book> createNamedQuery = entityManager.createNamedQuery(
					"Book.getAll", Book.class);

			return createNamedQuery.getResultList();
		} catch (Exception e) {
			return null;
		}
	}

}